package com.study.util.api;

import com.study.config.SmsConfigProperty;
import com.study.util.HttpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

//视频第一节 21:50

@Component
@Slf4j
public class SmsApi {
    @Autowired
    private SmsConfigProperty smsConfigProperty;

    public void sendSms(String phone, String message) {
        String encodeMessage = encodeString(message);
        String url = "https://api.smsbao.com/sms?u="+smsConfigProperty.getUsername() + "&p="
                + smsConfigProperty.getPassword() + "&m=" + phone +"&c=" + encodeMessage;
        String result = HttpUtil.sendGetRequest(url);

        if(result.equals("0")) {
            log.info("{} send message: {} success", phone, message);
        } else {
            log.info("{} send message: {} failed, error code: {}", phone, message, result);
        }

    }


    private String encodeString(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }


    }
}
